from app import db

from . import admin
from flask import render_template, redirect, url_for, flash, session, request, jsonify
from app.models import *
from sqlalchemy import or_, and_
from functools import wraps
from decimal import *
from werkzeug.security import generate_password_hash
import pandas as pd
import os
import time
from datetime import datetime, date
import random
import numpy as np
import json
import copy


def admin_login(f):
    """
    登录装饰器
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):

        # print('session', session)
        if "admin" not in session:
            return redirect(url_for("admin.login", next=request.url))
        return f(*args, **kwargs)

    return decorated_function

@admin.route("/")
@admin_login
def index():

    return render_template("admin/index.html")

@admin.route("/login/", methods=["GET","POST"])
def login():
    """
    登录功能
    """
    # 判断是否已经登录
    if request.method == "GET":
        print('session', session)
        if "admin" in session:
            return redirect(url_for("admin.index"))
        return render_template("admin/login.html")
    if request.method == "POST":
        post_data = request.form
        print(post_data)
        admin = Admin.query.filter_by(manager=post_data['manager']).first()
        if admin:
            if admin.check_password(post_data['password']):
                session["admin"] = post_data["manager"]  # 存入session
                session["admin_id"] = admin.id  # 存入session
                return redirect(url_for('admin.index'))
            else:
                error = '用户密码错误'
                return render_template("admin/login.html", error=error)
        else:
            error = '用户不存在'
            return render_template("admin/login.html", error=error)


@admin.route('/register', methods=["GET",  "POST"])
def register():
    if request.method == "POST":
        post_data = request.form
        print('[post_data]: ', request.form)

        has_data = Admin.query.filter_by(manager=post_data['manager']).first()
        print(has_data)
        if has_data == None:
            admin = Admin(
                manager = post_data['manager'],
                password = generate_password_hash(post_data['password'])
                # password=post_data['password']
            )
            db.session.add(admin)
            db.session.commit()
            data = {
                'code': 200,
                'msg': '注册成功'
            }
            return jsonify(data)
        return jsonify(post_data)

@admin.route('/user_manage', methods=["GET",  "POST"])
def user_manage():
    return render_template('admin/user_manage.html')

@admin.route('/role_manage', methods=["GET",  "POST"])
def role_manage():
    return render_template('admin/role_manage.html')
